import {
  Form,
  Button,
  Col,
  Row,
  Input,
  Select,
  DatePicker,
  message,
  Table,
  Popconfirm,
  InputNumber,
} from "antd";
import React, { Component } from "react";
import { Matchcompanylist, quotationAddNoRef } from "../../../services/auth";
import { getToken } from "../../../utils/auth";
import AddGoods from "./GoodsRow";

// form中的属性
const { Option } = Select;
const { RangePicker } = DatePicker;

export default class CreateQuotation extends Component {
  constructor(props) {
    super(props);
    this.handleCreateClick = this.props.handleCreateClick;
    // 这个是table的列属性
    this.columns = [
      {
        title: "产品编号",
        dataIndex: "goods_id",
      },
      {
        title: "产品名称",
        dataIndex: "goods_name",
      },
      {
        title: "订货数量",
        dataIndex: "quantity",
      },
      {
        title: "产品定价",
        dataIndex: "price",
      },
      {
        title: "折扣",
        dataIndex: "discount",
        width: "10%",
        editable: true,
      },
      {
        title: "产品价格",
        dataIndex: "current_price",
        editable: true,
      },
      {
        title: "operation",
        dataIndex: "operation",
        render: (_, record) =>
          this.state.dataSource.length >= 1 ? (
            <Popconfirm
              title="Sure to delete?"
              onConfirm={() => this.handleDelete(record.key)}
            >
              <a>Delete</a>
            </Popconfirm>
          ) : null,
      },
    ];
    this.state = {
      // 这个是商品数据
      dataSource: [],
      // 这个是可用于生成报价单的客户列表
      companyList: [],
      count: 0,
      discountRate: 100,
    };
    this.user = JSON.parse(getToken());
  }
  formRef = React.createRef();
  componentDidMount() {
    console.log(this.user);
    Matchcompanylist(this.user.id, this.user.authority).then(
      (response) => {
        //拿到我们想要渲染的数据(res)
        this.setState({
          companyList: response.data,
        });
      },
      (error) => {
        console.log("失败了", error);
      }
    );
  }
  // 传给抽屉用于新建商品的函数
  handleAddClick = (value) => {
    const { count, dataSource } = this.state;
    const newData = {
      key: count,
      ...value,
    };
    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1,
    });
  };
  // 用于编辑table的函数
  handleDelete = (key) => {
    const dataSource = [...this.state.dataSource];
    this.setState({
      dataSource: dataSource.filter((item) => item.key !== key),
    });
  };

  // 点击提交后触发的事件
  onFinish = (values) => {
    console.log(values);
    quotationAddNoRef({
      goods: this.state.dataSource,
      ...values,
      operator_id: this.user.id,
      req_deliv_date: values.req_deliv_date.format("YYYY-MM-DD"),
      ship_to_address: values.ship_to_address,
      valid_from: values.valid[0].format("YYYY-MM-DD"),
      valid_to: values.valid[1].format("YYYY-MM-DD"),
    }).then(
      (response) => {
        if (response.data.result === "success") {
          message.success("报价单" + response.data.quotation_id + "已创建成功");
          this.formRef.current.resetFields();
          this.handleCreateClick();
        } else {
          message.info("提交失败，请重试");
        }
      },
      (error) => {
        console.log("数据获取失败", error);
      }
    );
  };
  onReset = () => {
    this.formRef.current.resetFields();
  };
  componentDidUpdate() {
    const { dataSource } = this.state;
    let sum = 0;
    for (let j = 0; j < dataSource.length; j++) {
      sum += dataSource[j].current_price * parseInt(dataSource[j].quantity);
    }
    sum = sum * this.state.discountRate;
    sum = sum.toFixed(2);
    this.formRef.current.setFieldsValue({ total_price: sum });
  }

  discountChange(value) {
    this.setState({
      discountRate: value / 100,
    });
  }

  render() {
    const { dataSource } = this.state;
    return (
      <Form
        layout="vertical"
        hideRequiredMark
        onFinish={this.onFinish}
        ref={this.formRef}
      >
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              name="company"
              label="公司"
              rules={[{ required: true, message: "请选择公司" }]}
            >
              <Select placeholder="请选择公司" allowClear>
                {this.state.companyList.map((company) => (
                  <Option value={company.id} key={company.id}>
                    {company.id + " " + company.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="ship_to_address"
              label="送货地点"
              rules={[{ required: true, message: "请输入送货地点" }]}
            >
              <Input />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={7}>
            <Form.Item
              name="valid"
              label="生效期限"
              rules={[{ required: true, message: "请填写生效期限" }]}
            >
              <RangePicker />
            </Form.Item>
          </Col>
          <Col span={5}>
            <Form.Item
              name="req_deliv_date"
              label="送达日期"
              rules={[{ required: true }]}
            >
              <DatePicker />
            </Form.Item>
          </Col>
          <Col span={4}>
            <Form.Item
              name="discount"
              label="总折扣"
              rules={[{ required: true }]}
            >
              <InputNumber
                min={0}
                max={100}
                formatter={(value) => `${value}%`}
                parser={(value) => value.replace("%", "")}
                onChange={(number) => this.discountChange(number)}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="total_price"
              label="总价"
              rules={[{ required: true }]}
            >
              <Input disabled />
            </Form.Item>
          </Col>
        </Row>
        <AddGoods handleAddClick={this.handleAddClick} />
        <Table
          bordered
          dataSource={dataSource}
          columns={this.columns}
          pagination={{ pageSize: 4 }}
        />
        <Form.Item>
          <div
            style={{
              textAlign: "right",
              marginTop: "24px",
            }}
          >
            <Button onClick={this.onClose} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button htmlType="reset" style={{ marginRight: 8 }}>
              重置
            </Button>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </div>
        </Form.Item>
      </Form>
    );
  }
}
